package com.bs.resa.service.impl;

import com.bs.resa.common.DatetimeUtils;
import com.bs.resa.common.RedisUtils;
import com.bs.resa.dao.*;
import com.bs.resa.pojo.*;
import com.bs.resa.service.ProjectService;
import com.bs.resa.web.ProjectController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @Author lin
 * @date 2019/3/23 15:29
 */

@Service
public class ProjectServiceImpl implements ProjectService {
    private static Logger logger= LoggerFactory.getLogger(ProjectServiceImpl.class);
    private static   SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式

    protected Map<String, Object> resultMap = new LinkedHashMap<String, Object>();
    private Log log=new Log();
    @Resource
    RedisUtils redisUtils;
    @Value("${fastdfs_setting.IMAGE_SERVER_URL}")
    private String url;
    @Resource
    ProjectMapper projectMapper;
    @Resource
    AdminUserMapper adminUserMapper;
    @Resource
    TaskMapper taskMapper;
    @Resource
    UserProjectMapper userProjectMapper;
    @Resource
    LogMapper logMapper;

    /**
     * 添加项目表
     *
     * @return 项目自增主键
     */
    @Override
    public Integer insertProject(Project project) throws ParseException {
        projectMapper.insertProject(project);
        /*记录日志相关*/
        AdminUser adminUser=((AdminUser)redisUtils.getObject("userinfo"));
        log.setUserId(adminUser.getId());
        log.setData(df.parse(df.format(new Date())));
        log.setProjectId(Long.valueOf(project.getPid()));
        log.setDesc(adminUser.getAccount()+"创建新项目："+project.getPname()+"-结束时间为："+df.format(project.getPendDate()));
        logMapper.insertLog(log);
        return project.getPid();
    }

    /**
     * 查询所有项目
     *
     * @return
     */
    @Override
    public List<Map<String, Object>> queryAll(String projectName) {
        //获取所有的项目
        List<Map<String, Object>> projectList=projectMapper.queryAll(projectName);
        for(Map<String,Object> map:projectList){
           logger.info("==================条记录==============");

            //替换数据库文件路径
//            System.out.println((String)map.get("pcreateUserid"));
//            System.out.println((String)map.get("mainUserPath"));
            map.put("mainUserPath2",url);

            //获得项目的id
            Integer projectId= (Integer) map.get("pid");
            //获得项目参与人的id
            //获得项目的id
            Long pcrateUserid= (Long) map.get("pcrateUserid");
            //查询创建者信息
            AdminUser adminUser=adminUserMapper.queryUserById(String.valueOf(pcrateUserid));
            if (adminUser != null) {
                map.put("mainUserPath", adminUser.getFilepath());
            } else {
                map.put("mainUserPath", "");
            }

            //查询参与人列表
            List<AdminUser> adminUserList=adminUserMapper.queryUserByParticipant(String.valueOf(projectId));
            map.put("participant",adminUserList);

            float sum;
            if((Long)map.get("pStatusId")==1){
                sum=0.00f;
            }else {
                //项目进度
                int i, j, succ;
                i = taskMapper.queryTaskByProject1(String.valueOf(projectId));
                j = taskMapper.queryTaskByProject2(String.valueOf(projectId));
                succ = taskMapper.queryTaskByProject3(String.valueOf(projectId));
                int count=taskMapper.getCountTask(String.valueOf(projectId));
                if(succ==count){
                    //更新项目状态
                    projectMapper.updateStatusSuccess(String.valueOf(projectId));
                }

                logger.info(String.valueOf(i));
                logger.info(String.valueOf(j));
                logger.info(String.valueOf(succ));
                if(succ==0){
//                    System.out.println("sdssds");
                    sum=0.00f;
                }else{
                    sum = (float)succ / (i + j + succ);
                }



            }

            map.put("progress",(int)(sum*100)+"%");

        }


        return projectList;
    }

    /**
     * 获取项目概述图表的数据
     *
     * @param pid
     * @return
     */
    @Override
    public Map<String, Object> getDetail(String pid) {
        Map<String,Object> count=new HashMap<>();
        Map<String,Object> map=new HashMap<>();
        Map<String,Object> map2=new HashMap<>();
        map.put("01",0);map.put("02",0);map.put("03",0);map.put("04",0);map.put("05",0);map.put("06",0);
        map.put("07",0);map.put("08",0);map.put("09",0);map.put("10",0);map.put("11",0);map.put("12",0);
        map2.put("01",0);map2.put("02",0);map2.put("03",0);map2.put("04",0);map2.put("05",0);map2.put("06",0);
        map2.put("07",0);map2.put("08",0);map2.put("09",0);map2.put("10",0);map2.put("11",0);map2.put("12",0);

        //总任务12月
        List<Map<String,Object>> list=taskMapper.getDetail(pid);
        List<Object> list1=new ArrayList<>();
        int sum=0;
        for(Map<String,Object> maps:list){
            map.put((String)maps.get("payTimeStr"),(Long)maps.get("total"));
            sum+=(Long)maps.get("total");
        }
        count.put("sum1",sum);
        list1.add(map.get("01"));list1.add(map.get("02"));list1.add(map.get("03"));list1.add(map.get("04"));list1.add(map.get("05"));list1.add(map.get("06"));
        list1.add(map.get("07"));list1.add(map.get("08"));list1.add(map.get("09"));list1.add(map.get("10"));list1.add(map.get("11"));list1.add(map.get("12"));
        //完成的任务getDetailSuccess
        //完成量12月
        List<Map<String,Object>> listSuccess=taskMapper.getDetailSuccess(pid);
        List<Object> list2=new ArrayList<>();
        int sum2=0;
        for(Map<String,Object> maps:listSuccess){
            map2.put((String)maps.get("payTimeStr"),(Long)maps.get("total"));
            sum2+=(Long)maps.get("total");
        }
        count.put("sum2",sum2);
        list2.add(map2.get("01"));list2.add(map2.get("02"));list2.add(map2.get("03"));list2.add(map2.get("04"));list2.add(map2.get("05"));list2.add(map2.get("06"));
        list2.add(map2.get("07"));list2.add(map2.get("08"));list2.add(map2.get("09"));list2.add(map2.get("10"));list2.add(map2.get("11"));list2.add(map2.get("12"));


        resultMap.put("map1",list1);
        resultMap.put("map2",list2);
        resultMap.put("count",count);
        return resultMap;
    }

    /**
     * 获得概述图表其他数据
     *
     * @param pid
     * @return
     */
    @Override
    public Map<String, Object> getDetailOther(String pid) throws ParseException {
        //项目参与人数
        List<UserProject> userProjects=userProjectMapper.getByPid(pid);
        resultMap.put("people",userProjects.size());
        //当前花费时间
        Project projects=projectMapper.queryById(pid);
        int day= daysBetween(projects.getPcreatedate(),new Date());
        if(day<0){
            day=0;
        }
        resultMap.put("nowDay",day);

        //项目预计时间
        int day2= daysBetween(projects.getPcreatedate(),projects.getPendDate());
        resultMap.put("endData",day2+2);

        //项目详情
        resultMap.put("detail",projects.getDescription());
        //项目负责人
        resultMap.put("mainPeople",adminUserMapper.queryUserById(String.valueOf(projects.getPuserid())));
        resultMap.put("projectName",projects.getPname());
        return resultMap;
    }

    /**
     * 根据 id 查询项目
     *
     * @param pid
     * @return
     */
    @Override
    public Map<String,Object> queryByPid(String pid) {
        redisUtils.set("pid",pid);
        Map<String,Object> result=new HashMap<>();
        Project project=projectMapper.queryById(pid);
        result.put("project",project);
        SimpleDateFormat dfs=new SimpleDateFormat("yyyy-MM-dd");
        dfs.format(project.getPcreatedate());
        dfs.format(project.getPendDate());
        result.put("start",dfs.format(project.getPcreatedate()));
        result.put("end",dfs.format(project.getPendDate()));
        return result;
    }

    /**
     * 更新基本信息
     *
     * @param project
     * @param pid
     * @return
     */
    @Override
    public boolean updataProjectInfo(Project project, String pid) throws ParseException {
        project.setPcreatedate(df.parse(df.format(df.parse(project.getStartStr()+" 00:00:00"))));
        project.setPendDate(df.parse(df.format(df.parse(project.getEndStr()+" 00:00:00"))));
        int i =projectMapper.updateInfo(project,pid);
        return i==0?false:true;
    }

    /**
     * 查询项目参与人员
     *
     * @return
     */
    @Override
    public Map<String, Object> queryUserProject() {
        Map<String,Object> map=new HashMap<>();
        logger.info("查询项目参与人员");
        StringBuffer stringBuffer=new StringBuffer();
        System.out.println("项目id:"+redisUtils.get("pid"));
        List<UserProject> userProjects=userProjectMapper.getByPid(redisUtils.get("pid"));
        System.out.println("参与人员:"+userProjects);
        for(UserProject userProject:userProjects){
            stringBuffer.append(userProject.getUid()+";");
        }
        map.put("data",stringBuffer);
        return map;
    }

    /**
     * 修改项目参与人员
     *
     * @param data
     * @return
     */
    @Override
    public boolean updateProjectUser(String data) {
        try {
            //删除项目参与人员
            int i=userProjectMapper.deleteByPid(redisUtils.get("pid"));
            String[] strings=data.split(";");
            for(String string:strings){
                if(string!=null && !string.equals("")){
                    userProjectMapper.insert(string,redisUtils.get("pid"));
                }
            }
        }catch (Exception e){
            return  false;
        }

        return true;
    }

    public  static  int daysBetween(Date date1,Date date2){
        Calendar cal=Calendar.getInstance();
        cal.setTime(date1);
        long time1=cal.getTimeInMillis();
        cal.setTime(date2);
        long time2=cal.getTimeInMillis();
        long between_days=(time2-time1)/(1000*3600*24);
        return Integer.parseInt(String.valueOf(between_days));
    }
}
